package com.wanfajie.smsdistribute.util

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.support.v4.content.ContextCompat
import android.util.Log
import com.wanfajie.smsdistribute.MyApplication
import com.wanfajie.smsdistribute.R
import java.lang.reflect.Field

private const val TAG = "permitUtil"

fun getPermissionLocateName(permission : String) : String {
    val parts = permission.split('.')
    val key = if (parts.isNotEmpty()) parts[parts.size-1] else permission

    val field: Field? = try {
        R.string::class.java.getField(key)
    } catch (e: Exception) {
        Log.w(TAG, "no string resource [$permission]", e)
        return key
    }

    val value = try {
        field?.get(null)
    } catch (e: Exception) {
        Log.w(TAG, "invoke field failure [$permission] $field", e)
        return key
    }

    val id = value as? Int ?: return key
    return MyApplication.context.getString(id)
}

fun hasPermission(ctx : Context, permission : String) : Boolean {
    return ContextCompat.checkSelfPermission(ctx, permission) == PackageManager.PERMISSION_GRANTED
}

fun hasPermissions(ctx : Context, vararg permissions: String) : Boolean {
    for (permission in permissions) {
        if (!hasPermission(ctx, permission)) return false
    }

    return true
}

fun getDeniedPermissions(ctx : Context, vararg permissions : String): List<String> {
    val results = ArrayList<String>()

    for (permission in permissions) {
        if (!hasPermission(ctx, permission)) {
            results.add(permission)
        }
    }

    return results
}


private val MI_SET : Set<String> by lazy { setOf("REDMI", "XIAOMI") }

private fun logJumpFailure(brand: String, e: Exception) {
    Log.w(TAG, "跳转失败$brand (${Build.BRAND}:${Build.MODEL}:${Build.VERSION.SDK_INT})", e)
}
fun jumpPermissionSetting(ctx: Context): Boolean {

    return when (Build.BRAND.toUpperCase()) {
        "HUAWEI" -> jumpHUAWEIPermissionSetting(ctx)
        in MI_SET -> jumpMIUIPermissionSetting(ctx)
        "SAMSUNG" -> false  // 三星4.3可直接跳转
        else -> false
    }
        || jumpDefaultPermissionSetting(ctx)
        || jumpAppSettings(ctx)  // 都失败只好跳转到设置页
}

fun jumpMIUIPermissionSetting(ctx: Context): Boolean {
    val intent = Intent("miui.intent.action.APP_PERM_EDITOR")
    intent.setClassName("com.miui.securitycenter",
            "com.miui.permcenter.permissions.PermissionsEditorActivity")
    intent.putExtra("extra_pkgname", ctx.packageName)

    try {
        // MIUI 8
        ctx.startActivity(intent)
    } catch (e: Exception) {
        intent.setClassName("com.miui.securitycenter",
                "com.miui.permcenter.permissions.AppPermissionsEditorActivity")
        intent.putExtra("extra_pkgname", ctx.packageName)

        logJumpFailure("MIUI8", e)
        try {
            // MIUI 5/6/7
            ctx.startActivity(intent)
        } catch (e1: Exception) {
            logJumpFailure("MIUI5/6/7", e)
            return false
        }
    }

    return true
}

fun jumpHUAWEIPermissionSetting(ctx: Context): Boolean {
    val intent = Intent()
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    //华为权限管理
    val comp = ComponentName("com.huawei.systemmanager",
            "com.huawei.permissionmanager.ui.MainActivity")
    intent.component = comp

    return try {
        ctx.startActivity(intent)
        true
    } catch (e: Exception) {
        logJumpFailure("HUAWEI", e)
        false
    }
}

fun jumpDefaultPermissionSetting(ctx: Context): Boolean{
    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
    val uri = Uri.fromParts("package", ctx.packageName, null)
    intent.data = uri

    return try {
        ctx.startActivity(intent)
        true
    } catch (e: Exception) {
        Log.w(TAG, "跳转失败")
        logJumpFailure("", e)
        false
    }
}

fun jumpAppSettings(ctx: Context): Boolean {
    val intent = Intent()
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
    intent.data = Uri.fromParts("package", ctx.packageName, null)

    return try {
        ctx.startActivity(intent)
        true
    } catch (e: Exception) {
        logJumpFailure("设置页", e)
        false
    }
}
